<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>观看页面</title>
</head>
<body>
<h2>👀 观看中...</h2>
<video id="remoteVideo" style="width: 800px;height: 800px" autoplay playsinline muted></video>

<script>
    const room = new URLSearchParams(location.search).get("room") || "default";
    const ws = new WebSocket(`ws://${location.host}/ws/subscribe?room=${room}`);
    const pc = new RTCPeerConnection({
        // iceServers: [{ urls: "stun:127.0.0.1:3478" }],
        iceTransportPolicy:"all",
        iceServers:[],
    });

    const remoteVideo = document.getElementById("remoteVideo");
    let pendingCandidates = [];

    pc.ontrack = (event) => {
        if (remoteVideo.srcObject !== event.streams[0]) {
            remoteVideo.srcObject = event.streams[0];
        }
        remoteVideo.play();
        setInterval(()=>{
            // const [track] = event.streams[0].getTracks();
            // console.log("✅ ontrack", {
            //     id: track.id,
            //     kind: track.kind,
            //     muted: track.muted,
            //     enabled: track.enabled,
            //     readyState: track.readyState
            // });
            //
            // track.onunmute = () => {
            //     console.log("✅ 视频轨道 unmuted，准备播放");
            // };
        },1000)
    };

    pc.onicecandidate = (event) => {
        // if (event.candidate) {
        //     ws.send(JSON.stringify({ type: "candidate", candidate: event.candidate }));
        //     console.log("ICE Candidate:", event.candidate.candidate);
        // }
        if (event.candidate) {
            const candidateStr = event.candidate.candidate;
            console.log("ICE Candidate:", candidateStr);

            if (candidateStr.includes("typ host")) {
                console.log("✅ 本地 host 候选，使用局域网直连");
            }

            ws.send(JSON.stringify({ type: "candidate", candidate: event.candidate }));
        } else {
            console.log("❄️ ICE gathering complete");
        }
    };

    ws.onmessage = async (event) => {
        const msg = JSON.parse(event.data);

        if (msg.type === "offer") {
            console.log("📩 收到 offer");
            await pc.setRemoteDescription(new RTCSessionDescription({
                type: "offer",
                sdp: msg.sdp
            }));

            // 先添加缓存的候选 ★ 关键修改 ★
            for (const c of pendingCandidates) {
                try {
                    await pc.addIceCandidate(c);
                } catch (e) {
                    console.error("添加候选失败:", e);
                }
            }
            pendingCandidates = [];  // 清空缓存

            const answer = await pc.createAnswer();
            await pc.setLocalDescription(answer);

            ws.send(JSON.stringify({
                type: "answer",
                sdp: answer.sdp
            }));

        } else if (msg.type === "candidate") {
            const candidate = new RTCIceCandidate(msg.candidate);
            if (pc.remoteDescription && pc.remoteDescription.type) {
                await pc.addIceCandidate(candidate);
            } else {
                pendingCandidates.push(candidate);
            }
        }
    };
    pc.oniceconnectionstatechange = async () => {
        console.log("ICE connection state:", pc.iceConnectionState);
    };
    window.addEventListener("beforeunload", () => {
        ws.close();
        pc.close();
    });
    setTimeout(() => {
        console.warn("Ipc.iceConnectionState:",pc.iceConnectionState);
        if (pc.iceConnectionState !== 'connected') {
            console.warn("ICE连接超时，尝试重新连接");
            // location.reload();
        }
    }, 10000)
</script>
</body>
</html>
